package com.bodacn.keypoint;

import android.content.Context;
import android.view.KeyEvent;
import android.widget.EditText;

public class ScannerManager {
    String codeStr = "";
    String deviceName ="";
    OnScanListener listener;
    boolean isInterrupt = true;
    EditText barcodeEdit;
    public ScannerManager(OnScanListener listener, Context context) {
        this.listener = listener;
        barcodeEdit=new EditText(context);
    }

    /**
     * 处理输入事件
     *
     * @param event
     * @return true 表示消费掉，拦截不在传递， false 不管
     */

    public boolean dispatchKeyEvent(KeyEvent event) {
        System.out.println(event);
        /**
         * 系统的软键盘  按下去是 -1, 不管，不拦截
         */
        if (event.getDeviceId() == -1) {
            System.out.println("event.getDeviceId()-return-"+event.getDeviceId());
            return false;
        }
        deviceName =event.getDevice().getName();
        barcodeEdit.dispatchKeyEvent(event);
        int keyCode = event.getKeyCode();
        //按下弹起，识别到弹起的话算一次 有效输入
        //只要是 扫码枪的事件  都要把他消费掉 不然会被editText 显示出来
        if (event.getAction()== KeyEvent.ACTION_MULTIPLE){
            codeStr=event.getCharacters();
            if (listener != null&&codeStr.length()>0) {
                listener.onResult(codeStr, deviceName);
                codeStr = "";
            }
        }
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            //识别到结束，当下使用的设备是  是还会有个KEYCODE_DPAD_DOWN 事件，不知道其它设备有没有  先忽略
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                if (listener != null) {
                    codeStr=barcodeEdit.getText().toString().trim();
                    listener.onResult(codeStr.replace("\n",""), deviceName);
                    barcodeEdit.setText("");
                }
            }

        }
        //都是扫码枪来的事件，选择消费掉
        return true;
    }

    public interface OnScanListener {

        void onResult(String code,String deviceName);
    }

    public void setInterrupt(boolean interrupt) {
        isInterrupt = interrupt;
    }
}
